package Pattern.ObserverPattern.program4;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Test4 {
    public static void main(String[] args) {
        stockPrice stockPrice = new stock_im();
        Observer1 observer1 = new Stock1("MI能源", 19.9);
        Observer1 observer2 = new Stock1("蓝思科技", 28.8);
        Observer1 observer3 = new Stock1("东方环宇", 48.2);
        System.out.println("开盘值-------------------");
        stockPrice.add(observer1);
        stockPrice.add(observer2);
        stockPrice.add(observer3);
        //stockPrice.notifies();
        stockPrice.change(observer1, 15.4);
        stockPrice.change(observer2, 30);
    }
}

interface Observer1 {
    void update(double price);

    double getPrice();

    String getName();
}

class Stock1 implements Observer1 {
    private String name;
    private double price;

    public Stock1(String name, double price) {
        this.name = name;
        this.price = price;
        display();
    }

    private void display() {
        System.out.println(name + "     " + price + "RMB");
    }

    @Override
    public void update(double price) {
        System.out.println(name + "     " + price + "RMB     与上期相比" + Math.round((price - this.price) * 10) / 10.0 + "RMB");
        this.price = price;
    }

    @Override
    public double getPrice() {
        return price;
    }

    @Override
    public String getName() {
        return name;
    }
}

abstract class stockPrice {
    protected List<Observer1> observers = new ArrayList<>();

    public void add(Observer1 observer) {
        observers.add(observer);
    }

    public void remove(Observer1 observer) {
        observers.remove(observer);
    }

    public abstract void notifies(Observer1 observer);

    public abstract void change(Observer1 observer, double newPrice);
}

class stock_im extends stockPrice {
    private double newPrice;

    @Override
    public void notifies(Observer1 observer) {
        if (observers.contains(observer)) {
            observer.update(newPrice);
        }
        Observer1 observer1 = null;
        Iterator<Observer1> iterators = observers.iterator();
        while (iterators.hasNext()) {
            observer1 = iterators.next();
            if (observer != observer1) {
                System.out.println(observer1.getName() + "     " + observer1.getPrice() + "RMB");
            }
        }
    }

    @Override
    public void change(Observer1 observer, double newPrice) {
        this.newPrice = newPrice;
        notifies(observer);
    }
}